package com.zzh.zzhaiagent.wx.controller;

import com.zzh.zzhaiagent.protection.rate.RateLimiter;
import com.zzh.zzhaiagent.protection.rate.resolver.ClientIpRateLimiterKeyResolver;
import com.zzh.zzhaiagent.utils.ResultUtils;
import com.zzh.zzhaiagent.websocket.adapter.WebSocketAdapter;
import com.zzh.zzhaiagent.websocket.domain.vo.response.WSBaseResp;
import com.zzh.zzhaiagent.websocket.domain.vo.response.WSLoginUrl;
import com.zzh.zzhaiagent.wx.service.WxMsgService;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

/**
 * Description: 微信api交互接口
 * Author: ZZH
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/wx/portal/public")
public class WxPortalController {

    private final WxMpService wxService;// 微信开发包的service
    private final WxMpMessageRouter messageRouter;// 微信消息路由器
    private final WxMsgService wxMsgService;//自己的业务service

    private final WxMpService wxMpService;// 微信开发包的service

    /**
     * 用于验签 - 微信服务器的接口
     * 主要就是微信服务器需要去看到你的后端服务器是否正常
     * @param signature      签名
     * @param timestamp      时间戳
     * @param nonce          随机数
     * @param echostr        随机字符串
     * @return echostr
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    @RateLimiter(keyResolver = ClientIpRateLimiterKeyResolver.class,count = 5,time = 60)//针对IP进行限流，一分钟内访问5次
    public String authGet(@RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {

        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature,
                timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }


        if (wxService.checkSignature(timestamp, nonce, signature)) {// 校验签名 如果校验成功就返回echostr
            return echostr;// 原样返回echostr 微信服务器去查看是否返回的字符串就是微信传递的字符串
        }

        return "非法请求";
    }

    /**
     * 用于获取用户授权 - 微信网页授权 回调接口
     * 同时重定向
     * @param code
     * @return
     */
    @GetMapping("/callBack")
    public RedirectView callBack(@RequestParam String code) {
        try {
            WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxService.getOAuth2Service().getUserInfo(accessToken, "zh_CN");
            // 授权 & 保存用户信息
            wxMsgService.authorize(userInfo);
        } catch (Exception e) {
            log.error("callBack error", e);
        }
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("http://localhost:5173/home");//回到授权成功页面
        return redirectView;
    }

    /**
     * 用于接收微信服务器的消息 - 路由到对应的handler
     * @param requestBody
     * @param signature
     * @param timestamp
     * @param nonce
     * @param openid
     * @param encType
     * @param msgSignature
     * @return
     */
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        log.info("\n接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);

        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            // 交给路由器处理
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
        }

        log.debug("\n组装回复信息：{}", out);
        return out;
    }

    /**
     * 获取登录二维码url
     * @return 登录二维码url
     * @throws WxErrorException 微信错误异常
     */
    @GetMapping("/getTicketUrl")
    public ResultUtils<String> wxGetTicketUrl() throws WxErrorException {
        // 生成随机码
        Integer code = (int) (Math.random() * 1000000);

        // 找微信申请拿到登录二维码,临时二维码有效期1小时
        int timeout = 3600;
        WxMpQrCodeTicket wxMpQrCodeTicket = wxMpService.getQrcodeService().qrCodeCreateTmpTicket(code,timeout);
        return ResultUtils.ok(wxMpQrCodeTicket.getUrl());
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }

        return null;
    }
}
